package vip.mengqin.diandezhun.ui.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.baselibrary.interface_.CommCallBack;
import com.android.baselibrary.interface_.OkHttpCallBack;
import com.android.baselibrary.responce.BaseResponce;
import com.android.baselibrary.tool.AndPermisionUtil;
import com.android.baselibrary.tool.CommLoading;
import com.android.baselibrary.tool.CommToast;
import com.android.baselibrary.tool.Log;
import com.android.baselibrary.view.Comm_HeadView;
import com.android.baselibrary.view.MultiStateView;
import com.android.commcount.Lib_CommCount;
import com.android.commcount.bean.CommCount_Type;
import com.android.commcount.request.Recharge_Price_Item_Request;
import com.android.commcount.responce.RechargePriceData;
import com.google.gson.Gson;
import com.yanzhenjie.permission.runtime.Permission;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import vip.mengqin.diandezhun.R;
import vip.mengqin.diandezhun.adapter.RechargeCenter_ListAdapter;
import vip.mengqin.diandezhun.manager.API_Manager;
import vip.mengqin.diandezhun.responce.CreateOrderData;
import vip.mengqin.diandezhun.responce.RechargeData;

/**
 * 充值中心
 */
public class RechargeCenterActivity extends BaseActivity {

    @BindView(R.id.multiplestatusView)
    MultiStateView multiplestatusView;
    @BindView(R.id.comm_title)
    Comm_HeadView comm_title;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;

    RechargeCenter_ListAdapter adapter;
    CommCount_Type countType;
    int templateId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_recharge_center;
    }

    @Override
    protected void initView() {
        comm_title.setTitle("充值中心");
        comm_title.setRightText("增加", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adapter.addUser();
            }
        });

        adapter = new RechargeCenter_ListAdapter(mContext, callBack);
        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerview.setAdapter(adapter);

    }

    CommCallBack callBack = new CommCallBack() {
        @Override
        public void onResult(Object obj) {
            if ("change".equals(obj.toString())) {
                recharge_price();
            } else if ("toContact".equals(obj.toString())) {
                toContact();
            }
        }
    };


    @Override
    protected void initData() {
        templateId = getIntent().getIntExtra("templateId", 0);

//        String str = getIntent().getStringExtra("countType");
//        countType = new Gson().fromJson(str, CommCount_Type.class);
        Lib_CommCount.getInstance().getTypeList(mContext, new CommCallBack() {
            @Override
            public void onResult(Object obj) {
                List<CommCount_Type> commCountTypes = (List<CommCount_Type>) obj;
                for (CommCount_Type item : commCountTypes) {
                    if (item.id == templateId) {
                        countType = item;
                    }
                }
            }
        });

        recharge();
        recharge_price();
    }

    //获取充值面值
    private void recharge() {
        API_Manager.recharge(mContext, templateId, new OkHttpCallBack<BaseResponce<List<RechargeData>>>() {
            @Override
            public void onSuccess(BaseResponce<List<RechargeData>> baseResponce) {
                adapter.setRechargeDataList(baseResponce.getData());
                adapter.addUser();
            }

            @Override
            public void onFailure(BaseResponce<List<RechargeData>> baseResponce) {
                CommLoading.dismissLoading();
                CommToast.showToast(mContext, baseResponce.message);
            }
        });
    }

    //实时获取当前已添加联系人获取当前的总价格和折扣
    private void recharge_price() {
        List<Recharge_Price_Item_Request> items = adapter.getRequestList();
        API_Manager.recharge_price(mContext, templateId, items, new OkHttpCallBack<BaseResponce<RechargePriceData>>() {
            @Override
            public void onSuccess(BaseResponce<RechargePriceData> baseResponce) {
                adapter.setRechargePriceData(baseResponce.getData());
            }

            @Override
            public void onFailure(BaseResponce<RechargePriceData> baseResponce) {
                CommLoading.dismissLoading();
//                CommToast.showToast(mContext, baseResponce.message);
            }
        });
    }

    //充值统一下单
    private void recharge_recharge() {
        List<Recharge_Price_Item_Request> items = adapter.getRequestList();
        API_Manager.recharge_recharge(mContext, templateId, items, new OkHttpCallBack<BaseResponce<CreateOrderData>>() {
            @Override
            public void onSuccess(BaseResponce<CreateOrderData> baseResponce) {
                CreateOrderData data = baseResponce.getData();
                toPay(data);
            }

            @Override
            public void onFailure(BaseResponce<CreateOrderData> baseResponce) {
                CommLoading.dismissLoading();
//                CommToast.showToast(mContext, baseResponce.message);

                CreateOrderData data = baseResponce.getData();
                toPay(data);
            }
        });
    }

    private void toPay(CreateOrderData data )
    {
        Intent intent = new Intent(mContext, PayActivity.class);
        intent.putExtra("orderId", data.orderId);
        intent.putExtra("orderName", countType.title);
        intent.putExtra("price", adapter.rechargePriceData.allPrice);
        startActivity(intent);
    }


    @OnClick({R.id.csb_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.csb_ok:
                recharge_recharge();
                break;
        }
    }


    private void toContact() {
        AndPermisionUtil.requstPermision(mContext, new AndPermisionUtil.PermisionCallBack() {
            @Override
            public void onGranted() {
                intentToContact();
            }

            @Override
            public void onDenied() {
                CommToast.showToast(mContext, "没有通讯录权限");
            }
        }, Permission.READ_CONTACTS);
    }

    private void intentToContact() {
        // 跳转到联系人界面
        Intent intent = new Intent();
        intent.setAction("android.intent.action.PICK");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setType("vnd.android.cursor.dir/phone_v2");
        startActivityForResult(intent, 10001);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10001) {
            if (data != null) {
                Uri uri = data.getData();
                String phoneNum = null;
                String contactName = null;
                // 创建内容解析者
                ContentResolver contentResolver = getContentResolver();
                Cursor cursor = null;
                if (uri != null) {
                    cursor = contentResolver.query(uri,
                            new String[]{"display_name", "data1"}, null, null, null);
                }
                while (cursor.moveToNext()) {
                    contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    phoneNum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }
                cursor.close();
                //  把电话号码中的  -  符号 替换成空格
                if (phoneNum != null) {
                    phoneNum = phoneNum.replaceAll("-", " ");
                    // 空格去掉  为什么不直接-替换成"" 因为测试的时候发现还是会有空格 只能这么处理
                    phoneNum = phoneNum.replaceAll(" ", "");
                }

                Log.i("phoneNum:" + phoneNum);
                adapter.setContact(phoneNum);
            }
        }
    }
}
